package cn.itcast.mybatis.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;



/**
 * jdbc连接数据库
 * @author 16604
 *
 */
public class JdbcTest {
	
	public static void main(String[] args) {
		
		Connection connection = null;
		
		PreparedStatement preparedStatement = null;
		
		ResultSet resultSet = null;
		
		try {
			
			//加载数据库驱动
			Class.forName("com.mysql.jdbc.Driver");
			
			//通过数据库驱动管理连接数据库
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEcoding=utf-8","root","root");
			
			//写sql语句
			String sql = "select * from user where id = ?";
			
			//通过预处理获得sql语句
			preparedStatement = connection.prepareStatement(sql);
			
			//通过预处理，处理参数
//			preparedStatement.setString(1, "王五");
			preparedStatement.setInt(1, 27);
			
			//得到结果集
			resultSet = preparedStatement.executeQuery();
			
			//遍历结果集,从1开始
			while(resultSet.next()) {
				System.out.println(resultSet.getString("id")+" "+resultSet.getString("username"));
			}
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			closeQuiety(resultSet);
			closeQuiety(preparedStatement);
			closeQuiety(connection);
		}
		
	}
	
	private static void closeQuiety(AutoCloseable closeable) {
		if(closeable!=null) {
			try {
				closeable.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
